package com.mstore.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.mstore.interceptor.Authority;
import com.mstore.pojo.Account;
import com.mstore.pojo.Member;
import com.mstore.pojo.Shop;
import com.mstore.pojo.User;
import com.mstore.service.MemberService;
import com.mstore.service.SMSLogService;
import com.mstore.service.ShopService;
import com.mstore.service.UserService;
import com.mstore.util.CookieUtils;

/**
 * 
 * 
 * 分店信息操作
 */
public class UserAction extends BaseAction implements SessionAware,
		ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = -3078267949035651264L;

	private UserService userService;

	private ShopService shopService;

	private MemberService memberService;

	private SMSLogService smsLogService;

	private Map<String, Object> session;

	private HttpServletRequest request;

	private HttpServletResponse response;

	private User user;

	private List<User> users;

	private List<Shop> shops;

	private String result;

	private String json;

	private String userpassword;

	private String userId;

	private String userName;

	private String userMobile;

	private boolean check = false;

	private String passwordOld;

	private String userParamkey;

	private String useLoginName;

	private static Logger logger = Logger.getLogger(UserAction.class.getName());

	/**
	 * 添加分店管理员
	 */
	public String addUser() {
		Member member = new Member();
		String mobile = user.getMobile();
		String password = user.getPassword();
		try {
			member.setMobile(mobile.trim());
			if (memberService.checkMobile(member)) {
				result = "账号已被注册";
				return "errorAdd";
			}
		}
		catch (Exception e) {
			result = "请填写账号";
			return "errorAdd";
		}

		try {
			if (StringUtils.isBlank(password.trim())) {
				result = "请填写密码";
				return "errorAdd";
			}
		}
		catch (Exception e) {
			result = "请填写密码";
			return "errorAdd";
		}

		member.setPassword(password);
		member.setCreateTime(getCreateTime());
		member.setType(3);
		memberService.addMember(member);
		user.setCreateTime(getCreateTime());
		user.setMember(member);
		userService.addUser(user);

		return "addUser";
	}

	/**
	 * 查询全部分店管理员
	 * 
	 * @return
	 */
	public String getAllUser() {
		String temp = "error";
		Account account = (Account) session.get("account");
		if (account != null) {
			Shop shop = new Shop();
			shop.setEaId(account.getId());
			List<Shop> shops = shopService.getAllShop(shop);
			List<Long> shopIdls = new ArrayList<Long>();
			for (Shop shop2 : shops) {
				shopIdls.add(shop2.getId());
			}

			users = new ArrayList<User>();
			List<User> usersList = userService.getAllUser1();
			if (usersList.size() > 0) {
				for (User us : usersList) {
					if (shopIdls.contains(us.getShopId())) {
						Shop shop3 = new Shop();
						shop3.setId(us.getShopId());
						shop3 = shopService.getShopById(shop3);
						us.setShop(shop3);
						users.add(us);
					}
				}
				temp = "getAllUser";
			}
			else {
				temp = "nullUser";
			}
		}
		return temp;
	}

	/**
	 * 删除分店管理员
	 * 
	 * @return
	 */
	public String deleteUser() {
		this.user = userService.getOneUserAndMember(this.user);
		Member member = new Member();
		member.setId(this.user.getMember().getId());
		memberService.delMember(member);
		this.userService.deleteUser(this.user);
		return "deleteUser";
	}

	/**
	 * 获取店铺帐号
	 * 
	 * @return
	 */
	public String editUser() {
		if (this.user == null || this.user.getId().longValue() == 0) {
			// 跳回分店列表
			return "updateUser";
		}
		User user = (User) userService.getOneUser(this.user);
		Account account = (Account) session.get("account");
		if (user != null && account != null) {
			shops = getShopByUser(account);
			this.user = user;
			return "editUser";
		}
		return "error";
	}

	/**
	 * 更新账号信息
	 * 
	 * @return
	 */
	public String updateUser() {
		// 更新user
		if (user == null) {
			result = "手机号为空";
			return "errorUpdateUser";
		}

		String mobile = user.getMobile();
		if (StringUtils.isBlank(mobile)) {
			result = "手机号为空";
			return "errorUpdateUser";
		}

		mobile = mobile.trim();
		User u = userService.getOneUser(user);

		//if (!mobile.equals(u.getMobile())) {
			u.setMobile(mobile);

			Shop shop = new Shop();
			shop.setId(user.getShopId());
			shop = shopService.getShopById(shop);
			u.setShop(shop);
			u.setUserName(this.getUser().getUserName());
			userService.update(u);

			// 更新member
			Long memberId = userService.getMemberIdFromUser(user.getId());
			Member member = new Member();
			member.setId(memberId);
			member = memberService.getMemberById(member);
			member.setMobile(mobile);
			memberService.updateMember(member);
		//}

		return "updateUser";
	}

	/**
	 * 创建管理账号
	 * 
	 * @return
	 */
	public String getAllShop() {
		String temp = "error";
		Account account = (Account) session.get("account");
		if (account != null) {
			shops = getShopByUser(account);
			temp = "getAllShop";
		}
		return temp;
	}

	/**
	 * 获取企业下的所有店铺
	 * 
	 * @param account
	 * @return
	 */
	public List<Shop> getShopByUser(Account account) {
		Shop shop = new Shop();
		shop.setEaId(account.getId());
		List<Shop> shops = shopService.getAllShop(shop);
		return shops;
	}

	/**
	 * 获得全部分店管理员
	 * 
	 * @return
	 */
	public String getAllUser1() {
		String temp = "error";
		Account account = (Account) session.get("account");
		if (account != null) {
			Shop shop = new Shop();
			shop.setEaId(account.getId());
			List<Shop> shops = shopService.getAllShop(shop);
			List<Long> shopIdls = new ArrayList<Long>();
			for (Shop shop2 : shops) {
				shopIdls.add(shop2.getId());
			}

			users = new ArrayList<User>();
			List<User> usersList = userService.getAllUser1();
			if (usersList.size() > 0) {
				for (User us : usersList) {
					if (shopIdls.contains(us.getShopId())) {
						Shop shop3 = new Shop();
						shop3.setId(us.getShopId());
						shop3 = shopService.getShopById(shop3);
						us.setShop(shop3);
						users.add(us);
					}
				}
				temp = "getAllUser1";
			}
			else {
				temp = "nullUser1";
			}
		}

		return temp;
	}

	/**
	 * 分店用户查询
	 * 
	 * @return
	 */
	public String selectUser() {
		User user = (User) userService.getOneUser(this.user);
		Account account = (Account) session.get("account");
		if (user != null && account != null) {
			shops = getShopByUser(account);
			this.user = user;
			return "selectUserSuccess";
		}
		return "error";
	}

	/**
	 * 管理员修改密码
	 */
	public String updatePasswordByAccount() {
		User use = new User();
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isBlank(userId)) {
			result = "系统数据异常";
			return "error";
		}
		if (StringUtils.isBlank(userpassword)) {
			result = "系统数据异常";
			return "error";
		}
		use.setId(Long.parseLong(userId));
		User u = (User) userService.getOneUserAndMember(use);
		if (u != null) {
			use.setPassword(userpassword);
			userService.updatePasswordById(use);
			u.getMember().setPassword(userpassword);
			memberService.updateMember(u.getMember());
			// 重置session
			try {
				Object uObj = session.get("user");
				if (uObj != null) {
					User usr = (User) uObj;
					usr.setPassword(userpassword);
					session.put("user", usr);
				}
			}
			catch (Exception e) {
				logger.error("session为空", e);
			}
			map.put("temp", "密码修改成功");
			json = mapTojson(map);
			return "updatePasswordById";
		}
		return "updatePasswordById";
	}

	/**
	 * 分店修改密码
	 */
	public String updatePasswordById() {
		User use = new User();
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isBlank(userId)) {
			result = "系统数据异常";
			return "error";
		}
		if (StringUtils.isBlank(userpassword)) {
			result = "系统数据异常";
			return "error";
		}
		if (StringUtils.isBlank(passwordOld)) {
			result = "系统数据异常";
			return "error";
		}
		use.setId(Long.parseLong(userId));
		User u = (User) userService.getOneUserAndMember(use);
		if (u != null) {
			if (passwordOld.equals(u.getPassword())) {
				use.setPassword(userpassword);
				userService.updatePasswordById(use);
				u.getMember().setPassword(userpassword);
				memberService.updateMember(u.getMember());
				// 重置session
				try {
					Object uObj = session.get("user");
					if (uObj != null) {
						User usr = (User) uObj;
						usr.setPassword(userpassword);
						session.put("user", usr);
					}
				}
				catch (Exception e) {
					logger.error("session为空", e);
				}
				map.put("temp", "密码修改成功");
				json = mapTojson(map);
				return "updatePasswordById";
			}
			else {
				map.put("temp", "旧密码输入错误");
				json = mapTojson(map);
				return "updatePasswordById";
			}
		}
		return "updatePasswordById";
	}

	/************************************* 分店账号业务 ***********************************/
	/**
	 * 进入分店登陆页面
	 */
	@Authority(actionName = "muser", privilege = "pass")
	public String initLogin() {
		CookieUtils cookieUtils = new CookieUtils();
		user = cookieUtils.getUserFromCookie(request);
		if (user != null) {
			useLoginName = user.getLoginName();
			userParamkey = user.getParamKey();
		}
		return "toLoginJsp";
	}

	/**
	 * 分店用户登录 验证
	 */
	@Authority(actionName = "muser", privilege = "pass")
	public String login() {
		if (user == null || StringUtils.isBlank(user.getLoginName())
				|| StringUtils.isBlank(user.getPassword())
				|| StringUtils.isBlank(user.getParamKey())) {
			result = "用户名、密码或公司标示符不能为空！";
			return "musererror";
		}

		useLoginName = user.getLoginName();
		userParamkey = user.getParamKey();

		this.user.setPassword(user.getPassword());
		User user = (User) userService.findUser(this.user);
		if (user == null) {
			result = "用户名或密码不正确！";
			return "musererror";
		}
		session.put("user", user);

		CookieUtils cookieUtils = new CookieUtils();
		// 删除 可能已存在的cookie
		cookieUtils.delCookie(request, CookieUtils.USER_COOKIE);
		// 将user保存到cookie中
		Cookie cookie = cookieUtils.addUserInCookie(user);
		response.addCookie(cookie);

		return "login";
	}

	/**
	 * 安全退出
	 * 
	 * @return
	 */
	public String logout() {
		session.clear();
		return "logout";
	}

	/**
	 * 分店修改信息
	 * 
	 * @return
	 */
	public String updateMessage() {
		// 更新user
		if (user == null || StringUtils.isBlank(user.getMobile())) {
			result = "手机号为空";
			return "errorUpdate";
		}
		String mobile = user.getMobile();
		if (StringUtils.isBlank(mobile)) {
			result = "手机号为空";
			return "errorUpdate";
		}

		mobile = mobile.trim();

		User u = userService.getOneUser(user);

		if (!mobile.equals(u.getMobile())) {
			u.setMobile(mobile);
			userService.update(u);

			// 更新member
			Long memberId = userService.getMemberIdFromUser(user.getId());
			Member member = new Member();
			member.setId(memberId);
			member = memberService.getMemberById(member);
			member.setMobile(mobile);
			memberService.updateMember(member);

			// 重置session
			try {
				User usr = (User) session.get("user");
				usr.setMobile(mobile);
				session.put("user", usr);
			}
			catch (Exception e) {
				logger.error("session为空", e);
			}
		}

		// 更新shop地址
		Shop shop = new Shop();
		shop.setId(u.getShopId());
		shop.setAddress(user.getShop().getAddress());
		shopService.updateAddress(shop);

		return "updateMessageSuccess";
	}

	/**
	 * 验证修改信息是否重复
	 * 
	 * @return
	 */
	public String checkUpdateMessage() {
		Map<String, Object> map = new HashMap<String, Object>();

		if (StringUtils.isBlank(userMobile)) {
			check = false;
			map.put("check", check);
			map.put("message", "请填写登陆账号");
			json = mapTojson(map);
			return "checkUpdateMessage";
		}

		if (StringUtils.isBlank(userId)) {
			check = false;
			map.put("check", check);
			map.put("message", "系统数据异常");
			json = mapTojson(map);
			return "checkUpdateMessage";
		}

		user = new User();
		user.setId(Long.valueOf(userId));
		user = userService.getOneUserAndMember(user);
		user.setMobile(userMobile);
		int count = userService.getCountMemberByMobileOutSelf(user).intValue();
		if (count != 0) {
			check = false;
			map.put("check", check);
			map.put("message", "账号已被注册");
			json = mapTojson(map);
			return "checkUpdateMessage";
		}

		check = true;
		map.put("check", check);
		json = mapTojson(map);

		return "checkUpdateMessage";
	}

	/**
	 * 查询当前用户信息
	 * 
	 * @return
	 */
	public String selectUserMessage() {
		try {
			User u = (User) session.get("user");
			user = (User) userService.getOneUser(u);

			Shop shop = new Shop();
			shop.setId(user.getShopId());
			shop = shopService.getShopById(shop);
			user.setShop(shop);

		}
		catch (Exception e) {
			logger.error("session为空", e);
		}

		return "selectUserMessage";
	}

	/**
	 * 查询修改后的内容
	 * 
	 * @return
	 */
	public String selectUpdateUserMessage() {
		User u = (User) session.get("user");
		user = (User) userService.getOneUser(u);
		Shop shop = new Shop();
		shop.setId(user.getShopId());
		shop = shopService.getShopById(shop);
		user.setShop(shop);
		return "selectUpdateUserMessage";
	}

	/**
	 * 分店密码修改页面跳转
	 * 
	 * * @return
	 */
	public String gotoUpdateUserPsw() {
		return "gotoUpdateUserPsw";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ShopService getShopService() {
		return shopService;
	}

	public void setShopService(ShopService shopService) {
		this.shopService = shopService;
	}

	public List<User> getUsers() {
		return users;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public List<Shop> getShops() {
		return shops;
	}

	public void setShops(List<Shop> shops) {
		this.shops = shops;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public String getUserpassword() {
		return userpassword;
	}

	public void setUserpassword(String userpassword) {
		this.userpassword = userpassword;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserMobile() {
		return userMobile;
	}

	public void setUserMobile(String userMobile) {
		this.userMobile = userMobile;
	}

	public boolean isCheck() {
		return check;
	}

	public void setCheck(boolean check) {
		this.check = check;
	}

	public String getPasswordOld() {
		return passwordOld;
	}

	public void setPasswordOld(String passwordOld) {
		this.passwordOld = passwordOld;
	}

	public String getUserParamkey() {
		return userParamkey;
	}

	public void setUserParamkey(String userParamkey) {
		this.userParamkey = userParamkey;
	}

	public String getUseLoginName() {
		return useLoginName;
	}

	public void setUseLoginName(String useLoginName) {
		this.useLoginName = useLoginName;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public SMSLogService getSmsLogService() {
		return smsLogService;
	}

	public void setSmsLogService(SMSLogService smsLogService) {
		this.smsLogService = smsLogService;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

}
